<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\User;
use App\Models\MembershipCode;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use EasyWeChat\OfficialAccount\Application;

class ProcessFreeMembershipJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $openid;
    protected $wxapp;

    /**
     * 创建新的任务实例
     */
    public function __construct($openid)
    {
        $this->openid = $openid;
        $this->wxapp = new Application(config('wechat.official_account.default'));
    }

    /**
     * 执行任务
     */
    public function handle()
    {
        try {
            $result = $this->processFreeMembership();
            $this->sendCustomerServiceMessage($result);
        } catch (\Exception $e) {
            Log::error('免费会员异步处理失败：' . exception_to_string($e));
            $this->sendCustomerServiceMessage('处理失败，请稍后重试。');
        }
    }

    /**
     * 处理免费会员领取逻辑
     */
    private function processFreeMembership()
    {
        try {
            // 根据openid查找用户
            $user = User::where('openid', $this->openid)->first();

            if (!$user) {
                return '您还未绑定账户，请先在网页端登录并绑定微信，才能领取免费会员。';
            }

            // 检查用户是否已经领取过免费会员
            $hasRedeemed = MembershipCode::where('used_by', $user->id)
                ->where('type', 'day')
                ->where('duration', 7)
                ->where('is_used', true)
                ->where('description', '微信菜单免费领取')
                ->exists();

            if ($hasRedeemed) {
                return '您已经领取过免费会员，每个用户只能领取一次哦！';
            }

            DB::beginTransaction();

            try {
                // 创建一个7天的会员兑换码
                $membershipCode = new MembershipCode();
                $membershipCode->code = strtoupper(\Illuminate\Support\Str::random(16));
                $membershipCode->type = 'day';
                $membershipCode->duration = 7;
                $membershipCode->description = '微信菜单免费领取';
                $membershipCode->save();

                // 立即兑换会员
                $newExpiry = $membershipCode->redeem($user);

                DB::commit();

                return "恭喜您成功领取7天会员！\n会员有效期至：{$newExpiry->format('Y-m-d')}\n\n会员期间您可以无限使用所有功能，包括：\n- 无限次语音记账\n- 无限次图片记账\n- 无限次文字记账\n- 无限创建账本和分类\n- 无限使用定时记账\n\n更多会员权益详情：" . route('membership.benefits');

            } catch (\Exception $e) {
                DB::rollBack();
                Log::error('领取免费会员失败：' . exception_to_string($e));
                return '领取免费会员失败，请稍后重试。';
            }

        } catch (\Exception $e) {
            Log::error('处理免费会员事件失败：' . exception_to_string($e));
            return '处理失败，请稍后重试。';
        }
    }

    /**
     * 发送客服消息
     */
    private function sendCustomerServiceMessage($content)
    {
        try {
            $this->wxapp->getClient()->postJson('cgi-bin/message/custom/send', [
                'touser' => $this->openid,
                'msgtype' => 'text',
                'text' => [
                    'content' => $content
                ]
            ]);
        } catch (\Exception $e) {
            Log::error('发送客服消息失败：' . exception_to_string($e));
        }
    }

    /**
     * 处理任务失败
     */
    public function failed(\Throwable $exception)
    {
        Log::error('ProcessFreeMembershipJob 任务失败：' . exception_to_string($exception));
        
        try {
            $this->sendCustomerServiceMessage('系统繁忙，请稍后重试。');
        } catch (\Exception $e) {
            Log::error('发送失败消息时出错：' . exception_to_string($e));
        }
    }
}